package com.duoec.magichour.controller.api;

import com.duoec.magichour.core.annotation.Access;
import com.duoec.magichour.core.web.BaseApiController;
import com.duoec.magichour.dto.BaseResponse;
import com.duoec.magichour.dto.response.ArticleListItemDto;
import com.duoec.magichour.service.ArticleCollectionService;
import com.duoec.magichour.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 文章收藏接口
 */
@RestController
@RequestMapping("/api/article-collection")
public class ArticleCollectionApiController extends BaseApiController {
    @Autowired
    private ArticleService articleService;

    @Autowired
    private ArticleCollectionService articleCollectionService;

    /**
     * 获取已收藏文章列表
     *
     * @param pageNo   当前分页数，1为第一页
     * @param pageSize 每页最大记录数
     * @return
     */
    @Access
    @RequestMapping(method = RequestMethod.GET, value = "/collection")
    public BaseResponse<List<ArticleListItemDto>> collectionArticles(
            @RequestParam int pageNo,
            @RequestParam(required = false, defaultValue = "20") int pageSize
    ) {
        //获取当前用户的ID
        long userId = getUserInfo().getId();
        List<ArticleListItemDto> articleListList = articleService.getCollection(userId, pageNo, pageSize);
        return BaseResponse.success(articleListList);
    }

    /**
     * 收藏文章
     *
     * @param articleId 文章ID
     * @return
     */
    @Access
    @RequestMapping(method = RequestMethod.POST, value = "/{articleId:\\d+}")
    public BaseResponse<String> collect(@PathVariable long articleId) {
        Long authorId = articleService.getArticleAuthor(articleId);
        if (authorId == null) {
            //文章不存在
            return BaseResponse.notFindError("文章不存在！");
        }
        String articleCollectionId = articleCollectionService.collect(getUserInfo(), articleId, authorId);
        return BaseResponse.success(articleCollectionId);
    }
}
